using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npoi.Mapper;
using Publicuse.Appication;
using Publicuse.Autofac;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Util;
using ServiceStack;
using Spire.Pdf.Exporting.XPS.Schema;
using static FreeSql.Internal.GlobalFilter;

namespace Publicuse.Application
{
  public class OrganizationApplication
  {
    private static BaesApplication baseApplication;
    private static OrganizationApplication userApplication;

    public static OrganizationApplication GetApplication(ServiceContainer container)
    {
      baseApplication = new BaesApplication(container);
      return userApplication;
    }

    static OrganizationApplication()
    {
      userApplication = new OrganizationApplication();
    }

    /// <summary>
    /// 获取组织详细信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetDetail(int Id)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var list = baseApplication.mySqlSugar.QueryByExpression<Organization>(
          o => o.Id == Id,
          out var msg
        );
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          var Organization = list.FirstOrDefault();
          result.data = Organization;
        }
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 获取所有组织信息
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResult> GetListc()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var list = baseApplication.mySqlSugar.QueryByExpression<Organization>(
          o => o.status == 1,
          out var msg
        );
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          result.data = list;
          result.count = list.Count;
        }
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 获取组织信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetList(Organization query)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var tableName = TableAtributeUtil.GetTable<Organization>();
        string sql = query.GetQueryString<Organization>(null);
        List<Organization> organizations = new List<Organization>();
        OrganizationQuery oquery = new OrganizationQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = query.sortFile,
          sortType = query.sortType,
          files = query.files,
          pageIndex = query.pageIndex,
          pageSize = query.pageSize,
        };
        baseApplication
          .GetList<Organization>(
            oquery,
            false,
            (list, total) =>
            {
              if (list != null && list.Count > 0)
              {
                var oplist = list.Where(o => string.IsNullOrEmpty(o.parentId));
                oplist.ForEach(item =>
                {
                  Organization organization = new Organization()
                  {
                    name = item.name,
                    order = item.order,
                    parentId = item.parentId,
                    Remark = item.Remark,
                    Id = item.Id,
                    cTime = item.cTime,
                    uTime = item.uTime,
                    status = item.status,
                  };
                  var childrenlist = list.Where(o => o.parentId == item.Id.ToString()).ToList();
                  if (childrenlist != null && childrenlist.Count > 0)
                  {
                    organization.children = new List<Organization>();
                    childrenlist.ForEach(itemb =>
                    {
                      Organization organizationb = new Organization()
                      {
                        name = itemb.name,
                        order = itemb.order,
                        parentId = itemb.parentId,
                        Remark = itemb.Remark,
                        Id = itemb.Id,
                        cTime = itemb.cTime,
                        uTime = itemb.uTime,
                        status = itemb.status,
                      };
                      AddChildren(list, organizationb);
                      organization.children.Add(organizationb);
                    });
                  }
                  organizations.Add(organization);
                });
              }
              result.count = total;
              result.data = organizations;
            }
          )
          .GetAwaiter()
          .GetResult();
        return result;
      });
    }

    private static void AddChildren(List<Organization> list, Organization data)
    {
      var childrenlist = list.Where(o => o.parentId == data.Id.ToString()).ToList();
      if (childrenlist != null && childrenlist.Count > 0)
      {
        data.children = new List<Organization>();
        childrenlist.ForEach(itemb =>
        {
          Organization organization = new Organization()
          {
            name = itemb.name,
            order = itemb.order,
            parentId = itemb.parentId,
            Remark = itemb.Remark,
            Id = itemb.Id,
            cTime = itemb.cTime,
            uTime = itemb.uTime,
            status = itemb.status,
          };
          AddChildren(list, organization);
          data.children.Add(organization);
        });
      }
    }

    /// <summary>
    /// 检查组织名称是否存在
    /// </summary>
    /// <param name="sName"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckOrganizationName(
      string name,
      string loginUserCode,
      string Id = ""
    )
    {
      return await baseApplication.CheckDataExists<Organization>(
        BusinessType.organization,
        BusinessLogType.writeLogToDataBase,
        o => o.name == name && o.status != -9,
        "检查组织名称是否存在",
        Id
      );
    }

    /// <summary>
    /// 新增修改组织信息
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddOrUpdate(Organization info)
    {
      return await baseApplication.AddOrUpdate<Organization>(
        info,
        BusinessType.organization,
        BusinessLogType.writeLogToDataBase,
        null,
        o =>
        {
          QueryCacheUtil<Organization>.RemoveData(OrganizationQuery.GetExportName);
          DataCacheUtil.GetDataCacheUtil.RemoveData(TableAtributeUtil.GetTable<Organization>());
        }
      );
    }

    /// <summary>
    /// 删除组织信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResult> Delete(string Id, string loginUserCode, string type)
    {
      return await baseApplication.Delete<Organization>(
        Id,
        loginUserCode,
        type,
        BusinessType.organization,
        (a, b, info) =>
        {
          return info.name;
        }
      );
    }

    /// <summary>
    /// 还原组织信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> Reduction(string Id, string loginUserCode)
    {
      return await baseApplication.Reduction<Organization>(
        Id,
        loginUserCode,
        BusinessType.organization,
        (a, b, info) =>
        {
          return info.name;
        }
      );
    }
  }
}
